<template>
  <div class="login">
    <h2 class="title">登录</h2>
    <el-form
      ref="form"
      :model="form"
      label-width="60px"
      class="form"
      :rules="rules"
    >
      <el-form-item prop="username" label="账号">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
        <el-button @click="resetBtn">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { userLoginAPI } from "../apis/user";
import { setToken, setUserId } from "../utils/localData";
export default {
  data() {
    return {
      form: {
        // username: "13719539025",
        // password: "1234567890",
        // username: "13760719127",
        // password: "123456",
        username: "10086",
        password: "123",
      },
      rules: {
        username: [
          { required: true, message: "请输入正确手机号码", trigger: "blur" },
          // {
          //   pattern: /^1\d{10}$/,
          //   message: "长度在 3 到 11 个字符",
          //   trigger: "blur",
          // },
        ],
        password: [
          { required: true, message: "请输入正确密码", trigger: "blur" },
          {
            min: 3,
            max: 18,
            message: "长度在 3 到 18 个密码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(async (valid) => {
        console.log("是否所有表单都通过验证规则", valid);
        if (valid) {
          // alert("submit!");
          const res = await userLoginAPI(this.form);
          console.log(res);
          // 情况1：登录成功
          if (res.data.message === "登录成功") {
            // 保存 token 和 id
            setToken(res.data.data.token);
            setUserId(res.data.data.user.id);
            // 成功提示
            this.$message({ message: "恭喜你，登录成功", type: "success" });
            this.$router.push("/home");
          } else {
            // 情况2：登录失败提示
            this.$message({ message: "用户名或密码错误", type: "error" });
          }
        } else {
          this.$message({ message: "输入的数据不合法", type: "warning" });
          return false;
        }
      });
    },
    resetBtn() {
      this.$refs.form.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
.login {
  background-color: #f2f2f2;
  // 1vw    视口宽度(viewport width)的 1%
  // 1vh    视口高度(viewport height)的 1%
  height: 100vh;
  display: flex;
  align-items: center;
  flex-direction: column;
  padding-top: 10vh;
  box-sizing: border-box;
  .title {
    font-size: 30px;
    margin: 20px 0;
  }
  .form {
    background-color: #fff;
    width: 400px;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  }
}
</style>
